package dse;

import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;

public final class PropertiesUtil {
	private PropertiesUtil () {/**/}
	
	/**
	 * Preprocesses the properties object.  All it does is look for settings 
	 * of the form A=${B}, and as long as their is another setting B=C, then it
	 * changes the first setting to A=C.
	 *  
	 * @param props
	 */
	public static void preprocessProperties (Properties props)
	throws DseException
	{
		for (Object key : props.keySet()) {
			String v = props.getProperty((String)key);
			if (v.startsWith("${") && v.endsWith("}")) {
				v = v.substring(2, v.length()-1);
				String nv = props.getProperty(v);
				if (nv == null)
					throw new DseException (
							"In configuration, property '" + key + 
							"' references other property '" + v + "'. " +
							"However that property does not exist (is it " +
							"mispelled perhaps?)."
							);
				props.setProperty((String)key, nv);
			}
		}
	}
	
	/**
	 * Take a subset of the given properties that all start with the given 
	 * prefix.  Also, remove the prefix from the keys of the new set.
	 * 
	 * @param props
	 * @param prefix
	 * @return
	 */
	public static Map<String, String> collectSubset (
			Properties props, 
			String prefix
			)
	{
		Hashtable<String, String> subset = 
			new Hashtable<String, String>();
		for (Object k : props.keySet()) {
			String kas = (String)k;
			if (kas.startsWith(prefix))
				subset.put(
						kas.substring(prefix.length()),
						props.getProperty(kas));
		}
		return subset;
		
	}
}
